package softtech.apps.dangtinraovat;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.utils.StorageUtils;

import softtech.apps.model.Product;
import softtech.apps.model.ProductDetail;
import softtech.apps.model.User;
import softtech.apps.utilities.HttpRequest;
import softtech.apps.utilities.Utilities;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class ActivityProductDetail extends Activity {
	
	private Bitmap image1,image2,image3;
	private ProgressDialog pdia;
	private String TAG = "ActivityProductDetail";
	private Context context;
	
	DisplayImageOptions options;
	ImageLoaderConfiguration config;
	File cacheDir;
    String[] imageUrls;
	// Seller init view
	Button btContact;
	// Product init view
	ImageView img1,img2,img3;
	
	public ActivityProductDetail() {
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_product_detail);
		context = this;
        Intent i = getIntent();
	    int user_id = i.getIntExtra("user_id",0);
        int pServerId = i.getIntExtra("pServerId",0);
	     Log.d(TAG, "Seller ID = "+user_id + " Product ID ="+ pServerId); 
	     List<Integer> params = new ArrayList<>();
	     params.add(user_id);
	     params.add(pServerId);
	     AsyncUsers task = new AsyncUsers();
	     task.execute(params);
	     init_view();
	     cacheDir = StorageUtils.getCacheDirectory(context);
	     config = new ImageLoaderConfiguration.Builder(context)
         .threadPriority(Thread.NORM_PRIORITY - 2)
         .denyCacheImageMultipleSizesInMemory()
         .discCacheFileNameGenerator(new Md5FileNameGenerator())
         .tasksProcessingOrder(QueueProcessingType.LIFO)
         .writeDebugLogs() // Remove for release app
         .build();
	     options = new DisplayImageOptions.Builder()
         .showStubImage(R.drawable.draghere) // init image
         .showImageForEmptyUri(R.drawable.draghere) // image not found  
         .showImageOnFail(R.drawable.draghere)  // loading error
         .cacheInMemory(true) 
         .cacheOnDisc(true) 
         .displayer(new RoundedBitmapDisplayer(20)) 
         .build();
	     ImageLoader.getInstance().init(config);
	}
	
	public void init_view(){
		btContact = (Button) findViewById(R.id.btContact);
	}
	public void init_event_listener(){
		
	}
	private class AsyncUsers extends AsyncTask<List<Integer>, Void, ProductDetail> {
		
		@Override
		protected void onPreExecute(){ 
		   super.onPreExecute();
		        pdia = new ProgressDialog(ActivityProductDetail.this);
		        pdia.setMessage("Loading...");
		        pdia.show();    
		        
		}

		@Override
	    protected void onPostExecute(final ProductDetail p) {            
	        super.onPostExecute(p);
	        pdia.dismiss(); 
	        Log.d(TAG,"Full name onpostexcute"+p.getProduct().getpName());
	        String a = p.getProduct().getpImages();
	        Log.d(TAG, "Image tring = "+a);
	        JSONArray b = null;
			try {
				b = new JSONArray(a);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        
			String url0 = null;
			String url1 = null;
			String url2 = null;
			try {
				url0 = b.get(0).toString();
				url1 = b.get(1).toString();
				url2 = b.get(2).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        img1 = (ImageView) findViewById(R.id.imageviewOne);
	        img2 = (ImageView) findViewById(R.id.imageviewTwo);
	        img3 = (ImageView) findViewById(R.id.imageviewThree);
	        
	        ImageLoader.getInstance().displayImage(Utilities.APP_SERVER_ROOT + url0, img1,options);
	        ImageLoader.getInstance().displayImage(Utilities.APP_SERVER_ROOT + url1, img2,options);
	        ImageLoader.getInstance().displayImage(Utilities.APP_SERVER_ROOT + url2, img3,options);
	        
	        btContact.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(ActivityProductDetail.this,ActivityConversation.class);
			        int user_id = p.getUser().getId_server();
			        Log.d(TAG, "User Id clicked = "+user_id);
					intent.putExtra("user_id",String.valueOf(user_id));
					Log.d(TAG, "Gia tri cua user id = "+String.valueOf(user_id));
				    startActivity(intent);
				}
			});
	    }

		@Override
		protected ProductDetail doInBackground(List<Integer>... params) {
			// TODO Auto-generated method stub
			ProductDetail p = new ProductDetail();
            try {
            	HttpRequest req = new HttpRequest();
            	List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
            	nameValuePair.add(new BasicNameValuePair("uId",params[0].get(0).toString()));
            	nameValuePair.add(new BasicNameValuePair("pId",params[0].get(1).toString()));
            	String a = req.makeServiceCall(Utilities.APP_SERVER_URL_GET_PRODUCT_DETAILS,HttpRequest.POST,nameValuePair);;
            	try {
						JSONObject jsonObj = new JSONObject(a);
						JSONObject productDetail = jsonObj.getJSONObject("productDetail");
						
						JSONObject user = productDetail.getJSONObject("user");
						int id_server = Integer.parseInt(user.getString("user_id"));
						String fullname = user.getString("fullName");
						Log.d(TAG, "Full name = "+fullname);
						String address = user.getString("address");
						Log.d(TAG, "address = "+address);
						String email = user.getString("email");
						Log.d(TAG, "email = "+email);
						String phone_number = user.getString("phone_number");
						Log.d(TAG, "phone_number = "+phone_number);
						
						float rating = Float.parseFloat(user.getString("rating"));
						Log.d(TAG, "rating = "+rating);
						String avatar_path = user.getString("avatar_path");
						Log.d(TAG, "avatar_path = "+avatar_path);
						int type = Integer.parseInt(user.getString("type"));
						Log.d(TAG, "type = "+type);
						User u= new User(email,avatar_path,fullname,address,phone_number,rating,type,id_server);
						p.setUser(u);
						
						JSONObject product = productDetail.getJSONObject("product");
						int pServerId = Integer.parseInt(product.getString("pId"));
						int pCategory = Integer.parseInt(product.getString("pCategory"));
						int pColor = Integer.parseInt(product.getString("pColor"));
						String pName = product.getString("pName");
						float pPrice = Float.parseFloat(product.getString("pPrice"));
						float pSize = Float.parseFloat(product.getString("pSize"));
						String pDescription = product.getString("pDescription");
						String pImages = product.getString("pImages");
						String pOtherInfo = product.getString("pOtherInfo");
						String pTimeCreate = product.getString("pTimeCreate");
						int pUserId = Integer.parseInt(product.getString("pUserId"));
						
						Product pp = new Product(
								pCategory,
								pColor,
								pName,
								pSize,
								pPrice,
								pDescription,
								pImages,
								pOtherInfo,
								pTimeCreate,
								pServerId,
								pUserId
								);
						p.setProduct(pp);
					 return p;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				};
				
            } catch (Exception ex) {
            	ex.printStackTrace();
            }
			return null;
		}
}

}
